package com.adminsystem.java.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtil {

    /**
     * 根据 VO 类动态获取表头信息
     *
     * @param voClass VO 类型
     * @return 表头列表
     */
    public static List<List<String>> getWriteHead(Class<?> voClass) {
        List<List<String>> head = new ArrayList<>();
        Field[] fields = voClass.getDeclaredFields();
        for (Field field : fields) {
            ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
            if (annotation != null) {
                List<String> header = new ArrayList<>();
                for (String value : annotation.value()) {
                    header.add(value);
                }
                head.add(header);
            }
        }
        return head;
    }

    /**
     * 通用导出 Excel 方法
     *
     * @param dataList 数据集合
     * @param head     表头
     * @param fileName 文件名
     * @param response HttpServletResponse
     */
    public static void exportExcel(List<?> dataList, List<List<String>> head, String fileName, HttpServletResponse response) {
        try {
            WriteSheet sheet = EasyExcel.writerSheet(fileName).build();
            EasyExcel.write(response.getOutputStream())
                    .sheet("用户导入模版")
                    .doWrite(dataList);
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }

    /**
     * 通用导出 Excel 方法（基于 VO 类）
     *
     * @param dataList 数据集合
     * @param voClass  VO 类型
     * @param fileName 文件名
     * @param response HttpServletResponse
     */
    public static void exportExcel(List<?> dataList, Class<?> voClass, String fileName, HttpServletResponse response) {
        List<List<String>> head = getWriteHead(voClass);
        exportExcel(dataList, head, fileName, response);
    }
}